package com.yoso.auth.sdk;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.yoso.auth.sdk.config.JwtConfigurationProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Jwt工具
 * @link <a href="https://gitee.com/unicorn_dev/java-jwt/tree/3.9.0/"/>
 * @author shizejin
 * @date 2023/12/01 15:02
 */
@Component
public class JwtUtil {

    @Autowired
    private JwtConfigurationProperties jwtConfigurationProperties;


    public String generate(Map<String, String> claimMap) {
        final String issuer = jwtConfigurationProperties.getIssuer();
        final String secret = jwtConfigurationProperties.getSecret();
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTCreator.Builder builder = JWT.create()
                .withIssuer(issuer);
        if (claimMap != null && !claimMap.isEmpty()) {
            claimMap.forEach(builder::withClaim);
        }
        return builder.sign(algorithm);
    }

    public DecodedJWT verifier(String token) {
        final String issuer = jwtConfigurationProperties.getIssuer();
        final String secret = jwtConfigurationProperties.getSecret();
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier verifier = JWT.require(algorithm)
                .withIssuer(issuer)
                .build();
       return verifier.verify(token);
    }

}
